package com.jiuyou.clientController.user;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.Member;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.LoginMember;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/client/user")
public class ClientUserController extends BaseController {

    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private TokenService tokenService;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody)
    {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        Map map = loginService.login2(loginBody.getUsername(), loginBody.getPassword());
        LoginUser loginUser = (LoginUser)map.get("loginUser");
        SysUser userOne = userService.selectUserById(loginUser.getUserId());
        if(userOne.getRoles().size() > 0){
            userOne.setRoleId(userOne.getRoles().get(0).getRoleId());
        }
        ajax.put(Constants.TOKEN, map.get("token"));
        ajax.put("userOne", userOne);
        return ajax;
    }



    @RequestMapping("/getOpenId")
    public Map getOpenId(String code, Long userId) throws Exception {
        HashMap<String, Object> map = new HashMap<>();
        String openId=null;
        String unionid=null;

        String content = userService.converWechatOpenId(code);
        JSONObject jsonObject = JSON.parseObject(content);
        if (jsonObject.get("session_key") == null || jsonObject.get("openid") == null) {
            throw new Exception();
        }
        openId = jsonObject.getString("openid");
        unionid=jsonObject.getString("unionid");

        /*SysUser user2 = new SysUser();
        user2.setNotUserId(userId);
        user2.setOpenId(String.valueOf(openId));
        List<SysUser> SysUserList = userService.selectUserListForOpenId(userId,openId);
        if(SysUserList.size() > 0){
            SysUser suOne = userService.selectUserById(SysUserList.get(0).getUserId());
            map.put("success",true);
            map.put("msg","此openid已经赋值给"+suOne.getUserName());
            return map;
        }*/

        //记录open_id
        SysUser user = new SysUser();
        user.setUserId(userId);
        user.setOpenId(openId);
        user.setUnionId(unionid);
        userService.updateUser(user);

        SysUser userOne = userService.selectUserById(userId);

        map.put("success",true);
        map.put("userOne",userOne);
        map.put("openId",openId);
        return map;
    }


    /**
     * 重置密码
     */
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping("/updatePwd")
    public AjaxResult updatePwd(String oldPassword, String newPassword)
    {
        LoginUser loginUser = getLoginUser();
        String userName = loginUser.getUsername();
        String password = loginUser.getPassword();
        if (!SecurityUtils.matchesPassword(oldPassword, password))
        {
            return AjaxResult.error("修改密码失败，旧密码错误");
        }
        if (SecurityUtils.matchesPassword(newPassword, password))
        {
            return AjaxResult.error("新密码不能与旧密码相同");
        }
        if (userService.resetUserPwd(userName, SecurityUtils.encryptPassword(newPassword)) > 0)
        {
            // 更新缓存用户密码
            loginUser.getUser().setPassword(SecurityUtils.encryptPassword(newPassword));
            tokenService.setLoginUser(loginUser);
            return AjaxResult.success();
        }
        return AjaxResult.error("修改密码异常，请联系管理员");
    }

}
